package com.fuxin.app.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.Collection;

/**
 * @Author fuxin
 * @date 2019/3/10 21:54
 * @description
 */
@RestController
public class OAuthServer {

	@Autowired
	private RedisTemplate redisTemplate;

	@PreAuthorize("hasRole('ROLE_USER')  or #oauth2.clientHasRole('ROLE_CLIENT')" )
	@RequestMapping("/private/{id}")
	public String privateIndex(Principal principal, @PathVariable("id") int id){
		TokenStore tokenStore = new RedisTokenStore(redisTemplate.getConnectionFactory());
		Collection<OAuth2AccessToken> oAuth2AccessTokens
				= tokenStore.findTokensByClientIdAndUserName("app", principal.getName());
		oAuth2AccessTokens.forEach(token -> {
			((RedisTokenStore) tokenStore).removeAccessToken(token);
		});
		return "success" + id;

	}

}
